import router from './router'
import store from './store'
import NProgress from 'nprogress' 
import 'nprogress/nprogress.css' 
import { getToken } from '@/util/token-utils' 
import { generateIndexRouter } from '@/util/util'

NProgress.configure({ showSpinner: false }) 

const whiteList = ['/login'] 

router.beforeEach(async(to, from, next) => {

  NProgress.start()

  if(typeof(to.meta.title) == 'undefined') {
    document.title = '乾-元'
  } else {
    document.title = '乾-元 - ' + to.meta.title
  }

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name

      //这里判断使用hasGetUserInfo或store.getters.permissionList.length都行，道理一样
      //退出时需要将store.getters.name和permissionList都清理
      if(hasGetUserInfo.length === 0) {
       
        await store.dispatch('user/getInfo')
        store.dispatch('permission/getPermissionList').then(res => {
         
          let constRoutes = [];
          constRoutes = generateIndexRouter(res.data)

          //将404放到路由的最后
          constRoutes.push({
            path: '/404',
            component: () => import('@/views/404/404'),
            hidden: true
          })
          constRoutes.push({ path: '*', redirect: '/404', hidden: true })


          store.dispatch('permission/updateAppRouter', { constRoutes }).then(() => {
            // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表\
            
            router.addRoutes(store.getters.addRouters)

            next({ ...to, replace: true })
          })
        })
      } else {
        next()
      } 

    }
  } else {
   
    if (whiteList.indexOf(to.path) !== -1) {
      
      next()
    } else {
      
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
